#include "GameScene.h"
#include "FoodSpriteManager.h"

#include "SimpleAudioEngine.h"   

using namespace CocosDenshion;

CCArray *foodSprites;
int numSpritesMoved;
float SpriteMoveDuration;

long _nextTossTime;
TossType _currentTossType;
int _queuedForToss;
bool doubleSpeed;

GSpriteLayer::~GSpriteLayer(void)
{
	foodSprites->release();
	foodSprites =NULL; 
}
bool GSpriteLayer::init()
{
	bool bRet = false;
	do 
	{
		CC_BREAK_IF(! CCLayer::init());
		CCSize winSize =CCDirector::sharedDirector()->getWinSize();
		//----------------food--------------
		foodSprites = new CCArray();
		int numfoods = 5;

		char tmpstr[100] = {0};
		for (int j = 0; j < 6; j++)
		{
			for (int i = 0; i < numfoods; i++)
			{
				FoodSprite* pfood =FoodSpriteManager::sharedFoodSpriteManager()->createFood((FoodType)(j));
				pfood->setPosition(ccp(64 *(i+1),winSize.height  +64));
				this->addChild(pfood,1);
				foodSprites->addObject(pfood);
			}
		}
		for (int i = 6; i < 9; i++)
		{
			FoodSprite* pfood =FoodSpriteManager::sharedFoodSpriteManager()->createFood((FoodType)(i));
			pfood->setPosition(ccp(64 *(i+1),winSize.height  +64));
			this->addChild(pfood,1);
			foodSprites->addObject(pfood);
		}

		resetFoodSprite();


		bRet = true;
	} while (0);

	return bRet;
}



void GSpriteLayer::foodSpritesUpdata(float cctime)
{
	//CCSize winSize =CCDirector::sharedDirector()->getWinSize();
	//for (int i = 0; i < 10; i++)
	//{
	//	int c =foodSprites->count();
	//	CCObject *obj =	foodSprites->randomObject();
	//	CCSprite *pfood = (CCSprite*)(obj);
	//	CCSize fsize =pfood->getContentSize();
	//	/*	if(pfood->getPositionX() >winSize.width || pfood->getPositionX() <0 || pfood->getPositionY() >winSize.height || pfood->getPositionY() <0)
	//	{
	//	pfood->setPosition(ccp(fsize.width *i +fsize.width*0.5,winSize.height + fsize.height));
	//	pfood->stopAllActions();
	//	}*/
	//	if(pfood->numberOfRunningActions() == 0)
	//	{
	//		runSpritesMoveSequence(pfood);
	//		break;
	//	}
	//}
	CCSize winSize =CCDirector::sharedDirector()->getWinSize();

	CCObject * temp;
	CCARRAY_FOREACH(foodSprites, temp){
		FoodSprite* sprite = (FoodSprite*)temp;
		if(sprite->getState() == kStateTosseding){
			if(sprite->numberOfRunningActions() == 0)
			{
				runSpritesMoveSequence(sprite);
				break;
			}
			//------------

			if((sprite->getPositionX() < 34 || sprite->getPositionX() > winSize.width- 34) && sprite->getPositionY() >winSize.height -80)
			{
				sprite->setState(kStateTossed);
				sprite->stopAllActions();

				CCScaleTo * scale =CCScaleTo::create(0.5f,0.5);
				CCEaseBackInOut *ebi =CCEaseBackInOut::create(scale);

				CCRotateBy *rotate = CCRotateBy::create(0.5f,720);
				CCSpawn *spawn = CCSpawn::createWithTwoActions(rotate,ebi);
				CCHide *hide=CCHide::create();
				hide->setDuration(0.1f);
				CCCallFuncN * callDidDrop =CCCallFuncN::create(this ,callfuncN_selector(GSpriteLayer::spriteAwayCallback));
				CCSequence * sequence =CCSequence::create(spawn,hide,callDidDrop,NULL);

				sprite->runAction(sequence);
				SimpleAudioEngine::sharedEngine()->playEffect("PetSound00.mp3");
			}
			else if(sprite->getPositionY() < BOTTOMDISTANCE)
			{
				sprite->setState(kStateTossed);
				sprite->stopAllActions();
				sprite->setVisible(false);
				FoodSpriteManager::sharedFoodSpriteManager()->computeFoodSpriteScore(sprite);

			}
		}
	}

	this ->spriteLoop();
}

void GSpriteLayer::resetFoodSprite()
{
	CCSize winSize =WINSIZE;
	////CCObject *obj =foodSprites->lastObject();
	//CCSprite* f =(CCSprite*)(foodSprites->lastObject());
	//CCSize fsize =	f->getContentSize();
	//int  num = foodSprites->count();
	//for (int i = 0; i < num; i++)
	//{
	//	CCSprite *pfood = (CCSprite*)(foodSprites->objectAtIndex(i));
	//	pfood->setPosition(ccp(fsize.width *i +fsize.width*0.5,winSize.height + fsize.height));
	//	pfood->stopAllActions();
	//}

	CCObject * temp;
	CCARRAY_FOREACH(foodSprites, temp){
		FoodSprite* sprite = (FoodSprite*)temp;
		sprite->setVisible(true);
		sprite->setScale(1);
		sprite->stopAllActions();
		sprite->setPosition(ccp(0,winSize.height  +64));
		sprite->setState(kStateIdle);
	}

	this->unschedule(schedule_selector(GSpriteLayer::foodSpritesUpdata));
	this->schedule(schedule_selector(GSpriteLayer::foodSpritesUpdata));

	numSpritesMoved=0;
	SpriteMoveDuration =4.0f;
}


void GSpriteLayer::spriteLoop(){
	long curTime = millisecondNow();
	cocos2d::cc_timeval now;
		cocos2d::CCTime::gettimeofdayCocos2d(&now, NULL);
	CCLog("tv_sec : %lld", now.tv_sec);
	//CCLog("tv_usec : %lld", now.tv_usec);

	CCLog("curTime : %lld", curTime);
	if(curTime > _nextTossTime){
	//if(random1 == 1){
		CCObject* temp;

		/*	int chance = rand() % 8;
		if(chance == 0){
		CCARRAY_FOREACH(foodSprites, temp){
		FoodSprite* sprite = (FoodSprite*)temp;
		if(sprite->getState() == kStateIdle && sprite->getType() == kTypeBomb){
		this->tossSprite(sprite);
		SimpleAudioEngine::sharedEngine()->playEffect("toss_bomb.mp3");
		break;
		}
		}
		}*/

		int random = random_range(0, 8);

		FoodType type = (FoodType)random;
		if(_currentTossType == kTossConsecutive && _queuedForToss > 0){
			//SimpleAudioEngine::sharedEngine()->playEffect("toss_consecutive.mp3");
			CCARRAY_FOREACH(foodSprites, temp){
				FoodSprite* sprite = (FoodSprite*)temp;
				if(sprite->getState() == kStateIdle && sprite->getType() == type){
					this->tossSprite(sprite);
					_queuedForToss--;
					break;
				}
			}
		}else{
			_queuedForToss = random_range(3, 8);
			int tossType = random_range(0, 1);

			_currentTossType = (TossType)tossType;

			if(_currentTossType == kTossSimultaneous){
				//SimpleAudioEngine::sharedEngine()->playEffect("toss_simultaneous.mp3");
				CCARRAY_FOREACH(foodSprites, temp){
					FoodSprite* sprite = (FoodSprite*)temp;
					if(sprite->getState() == kStateIdle && sprite->getType() == type){
						this->tossSprite(sprite);
						_queuedForToss --;

						random = random_range(0, 5);
						type = (FoodType)random;

						if (_queuedForToss == 0)
						{
							break;
						}
					}
				}
			}else if(_currentTossType == kTossConsecutive){
				//SimpleAudioEngine::sharedEngine()->playEffect("toss_consecutive.mp3");
				CCARRAY_FOREACH(foodSprites, temp){
					FoodSprite* sprite = (FoodSprite*)temp;
					if(sprite->getState() == kStateIdle && sprite->getType() == type){
						this->tossSprite(sprite);
						_queuedForToss--;
						break;
					}
				}
			}
		}

		if(_queuedForToss == 0){
			float	_tossInterval = frandom_range(2, 3);
			_nextTossTime = curTime + _tossInterval * 1000.0f;
		}else{
			float _tossInterval = frandom_range(0.3f, 0.8f);
			_nextTossTime = curTime + _tossInterval * 1000.0f;
		}
	}
}

void GSpriteLayer::tossSprite(FoodSprite* sprite)
{
	CCSize winSize = CCDirector::sharedDirector()->getWinSize();
	CCPoint randomPosition = ccp(frandom_range(50.0f, winSize.width - 50.0f),winSize.height  +64.0f);
	//float randomAngularVelocity = CCRANDOM_MINUS1_1();

	//float xModifier = 50*(randomPosition.x - 100)/(winSize.width - 264);
	//float min = -25.0 - xModifier;
	//float max = 75.0 - xModifier;

	//float randomXVelocity = frandom_range(min,max);
	//float randomYVelocity = frandom_range(250, 300);

	sprite->setState(kStateTosseding);
	sprite->setPosition(randomPosition);
}

void GSpriteLayer::runSpritesMoveSequence(CCSprite* pfood)
{
	numSpritesMoved++;
	/*if(numSpritesMoved %8 == 0 && SpriteMoveDuration>2.0f)
	{
	SpriteMoveDuration -=0.1f;
	}*/
	CCSize winSize = CCDirector::sharedDirector()->getWinSize();
	float sec =SpriteMoveDuration *	pfood->getPositionY() /(winSize.height+pfood->getContentSize().height );


	CCPoint belowScreenPosition =ccp(pfood->getPositionX(), - pfood->getContentSize().height);
	CCMoveTo* move =CCMoveTo::create(sec,belowScreenPosition);
	CCCallFuncN * callDidDrop =CCCallFuncN::create(this ,callfuncN_selector(GSpriteLayer::spriteDidDropCallback));

	CCSequence * sequence =CCSequence::create(move,callDidDrop,NULL);

	int speed = doubleSpeed? 2 :1;
	CCSpeed * speedAction = CCSpeed::create(sequence,speed);
	speedAction->setTag(1);
	pfood->runAction(speedAction);

}



void GSpriteLayer::spriteDidDropCallback(CCNode * obj)
{
	FoodSprite * sprite =(FoodSprite*)obj;
	//CCPoint pos =sprite->getPosition();
	//CCSize sSize = CCDirector::sharedDirector()->getWinSize();
	//pos.y =sSize.height + sprite->getContentSize().height;
	//sprite->setPosition(pos);

	sprite->setState(kStateTossed);

	char  tmp[100] ={0};
	CCObject *temp;
	int mcount =0;
	CCARRAY_FOREACH(foodSprites, temp){
		FoodSprite* sprite = (FoodSprite*)temp;
		if(sprite->getState() == kStateIdle ){
			mcount++;
		}
	}
	sprintf(tmp, "Count -> %d   kStateTossed -> %d",foodSprites->count(),mcount);
	CCLog(tmp);
}

void GSpriteLayer::spriteAwayCallback(CCNode * obj)
{
	//obj->setVisible(false);
}


void GSpriteLayer::changeSpeed(bool isdoubleSpeed)
{
	doubleSpeed =isdoubleSpeed;
	CCObject *temp;
	int mcount =0;
	CCARRAY_FOREACH(foodSprites, temp){
		FoodSprite* sprite = (FoodSprite*)temp;
		if(sprite->getState() == kStateTosseding && sprite->numberOfRunningActions() >0)
		{
			int speed = doubleSpeed? 2 :1;
			CCSpeed * speedAction = (CCSpeed*)(sprite->getActionByTag(1));
			speedAction->setSpeed(speed);
		}
	}
}

